import { TournamentCacheService } from './tournament.cache.service';
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  HttpException,
  HttpStatus,
  Req,
} from '@nestjs/common';
import { TournamentService } from './tournament.service';
// import { UserService } from 'src/modules/user/user.service';
import { CreateTournamentDto } from './dto/create-tournament.dto';
import { UpdateTournamentDto } from './dto/update-tournament.dto';
import { EventTypeText, RoleEnum, TournamentStatusEnum } from 'src/common/constant/enums';
import logger from 'src/common/utils/log';
import { EventService } from '../event/event.service';
import { ApiBearerAuth, ApiBody, ApiOkResponse, ApiOperation, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { Auth } from 'src/common/decorators/auth.decorator';
import { Public } from 'src/common/decorators/public.decorator';
import { RequirePermission } from 'src/common/decorators/permission.decorator';
import { User } from '../user/entities/user.entity';
import { RequestUserDto } from '../auth/dto/request-user.dto';

@Auth()
@ApiBearerAuth() //
@Controller('tournament')
export class TournamentController {
  constructor(
    private readonly tournamentService: TournamentService,
    private readonly TournamentCacheService: TournamentCacheService,
    // private readonly userService: UserService,
    private readonly eventService: EventService,
  ) {}
  @ApiOperation({ summary: '创建锦标赛' })
  @ApiOkResponse({ description: '锦标赛创建成功' })
  @ApiBody({ type: CreateTournamentDto })
  @RequirePermission('1001002')
  @Post('add')
  async create(
    @Req() request,
    @Body() createTournamentDto: CreateTournamentDto,
  ) {
    const user = request.user;
    createTournamentDto.createBy = user.id;
    createTournamentDto.updateBy = user.id;
    createTournamentDto.status = TournamentStatusEnum.Created;
    if (
      createTournamentDto.categories &&
      createTournamentDto.categories.length > 0
    ) {
      createTournamentDto.categories.forEach((categoryItem) => {
        categoryItem.createBy = user.id;
        categoryItem.updateBy = user.id;
        if (categoryItem.events && categoryItem.events.length > 0) {
          categoryItem.events.forEach((eventItem) => {
            const selectEvent = Object.entries(EventTypeText).find((v) => {
              const [key] = v;
              return eventItem.type === parseInt(key);
            });
            eventItem.name = selectEvent[1];
            eventItem.createBy = user.id;
            eventItem.updateBy = user.id;
          });
        } else {
          throw new HttpException(
            '没有配置Event',
            HttpStatus.INTERNAL_SERVER_ERROR,
          );
        }
      });
    }
    logger.info(
      'trounament.controller.create: createTournamentDto',
      createTournamentDto,
    );
    const res = await this.tournamentService.create(createTournamentDto);
    // 将tournmentId 存给event
    const tournamentId = res.id;
    const updateEvents = [];
    if (res.categories && res.categories.length) {
      res.categories.forEach((categoryItem) => {
        if (categoryItem.events && categoryItem.events.length) {
          categoryItem.events.forEach((eventItem) => {
            eventItem.tournamentId = tournamentId;
            updateEvents.push(eventItem);
          });
        }
      });
    }
    await this.eventService.saveList(updateEvents);
    return res;
  }

  @Public()
  @RequirePermission('1001001')
  @Get('search')
  @ApiQuery({
    name: 'name',
    type: String,
    description: '锦标赛名称，用于模糊搜索',
    required: false,
  })
  @ApiQuery({
    name: 'status',
    enum: TournamentStatusEnum,
    description: '锦标赛状态',
    required: false,
  })
  @ApiQuery({
    name: 'size',
    type: Number,
    description: '每页显示的记录数，默认值为 10',
    required: false,
  })
  @ApiQuery({
    name: 'current',
    type: Number,
    description: '当前页码，默认值为 1',
    required: false,
  })
  async search(
    @Query('params') param?: { name: string; status: TournamentStatusEnum },
    @Query('size') limit?,
    @Query('current') page?,
  ) {
    const { name, status } = param || {};
    return await this.tournamentService.searchTournaments(
      name,
      status,
      page || 1,
      limit || 10,
    );
  }

  @Get('mylist')
  @RequirePermission('1001001')
  async findMyAll(@Req() request) {
    // logger.info('tournament.controller.findMyAll: request.user', request.user);
    const user = request.user;
    // 如果user.role 是admin 则返回所有, 否则返回createBy为user.id 的数据
    if ((user as RequestUserDto).roles.includes(RoleEnum.Admin)) {
      return await this.tournamentService.findAll();
    }
    return await this.tournamentService.findByCreateBy(user.id);
  }

  @RequirePermission('1001001')
  @Get('list')
  async list() {
    return await this.tournamentService.findAll();
  }

  @RequirePermission('1001001')
  @Get(':id')
  async findOne(@Param('id') id: string) {
    // return await this.tournamentService.findDetailById(+id);
    return await this.TournamentCacheService.findDetailById(+id);
  }

  @RequirePermission('1001003')
  @Patch(':id')
  async update(
    @Param('id') id: string,
    @Body() updateTournamentDto: UpdateTournamentDto,
  ) {
    return await this.tournamentService.update(+id, updateTournamentDto);
  }

  @RequirePermission('1001004')
  @Delete(':id')
  async remove(@Param('id') id: string) {
    return await this.tournamentService.remove(+id);
  }
}
